import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import '../App.css';

function AddressManagement() {
  const navigate = useNavigate();
  const [addressList, setAddressList] = useState<any[]>([]);
  const [showModal, setShowModal] = useState(false); // 控制模态框显示
  const [deleteId, setDeleteId] = useState(''); // 存储要删除的地址ID

  // 获取地址列表数据
  useEffect(() => {
    fetch('http://localhost:3000/list3')
      .then(res => res.json())
      .then(data => {
        if (data.code === 200) {
          // 确保将后端的mo字段映射到前端的isDefault字段
          const formattedList = (data.list2 || []).map(item => ({
            ...item,
            isDefault: item.mo
          }));
          setAddressList(formattedList);
        }
      })
      .catch(error => {
        console.error('获取地址列表失败:', error);
      });
  }, []);

  const exitManagement = () => {
    navigate('/zhi');
  };

  // 打开删除确认模态框
  const openDeleteModal = (id) => {
    setDeleteId(id);
    setShowModal(true);
  };

  // 关闭模态框
  const closeModal = () => {
    setShowModal(false);
  };

  // 确认删除地址
  const confirmDelete = () => {
    fetch(`http://localhost:3000/del?_id=${deleteId}`, {
      method: 'DELETE'
    })
      .then(res => res.json())
      .then(data => {
        if (data.code === 200) {
          // 从列表中移除删除的地址
          setAddressList(addressList.filter(item => item._id !== deleteId));
        }
        closeModal();
      })
      .catch(error => {
        console.error('删除地址失败:', error);
        closeModal();
      });
  };

  // 设置默认地址
  const setDefault = (id) => {
    // 找到要设置为默认的地址
    const addressToDefault = addressList.find(item => item._id === id);
    if (addressToDefault) {
      // 更新地址信息，设置为默认
      fetch('http://localhost:3000/update', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          _id: id,
          mo: true
        })
      })
        .then(res => res.json())
        .then(data => {
          if (data.code === 200) {
            // 先取消所有地址的默认状态
            const updatedList = addressList.map(item => ({
              ...item,
              isDefault: false
            }));
            // 然后设置当前地址为默认
            const newList = updatedList.map(item => {
              if (item._id === id) {
                return { ...item, isDefault: true };
              }
              return item;
            });
            setAddressList(newList);
          }
        })
        .catch(error => {
          console.error('设置默认地址失败:', error);
        });
    }
  };

  // 取消默认地址
  const cancelDefault = (id) => {
    fetch('http://localhost:3000/update', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        _id: id,
        mo: false
      })
    })
      .then(res => res.json())
      .then(data => {
        if (data.code === 200) {
          // 更新列表，取消默认
          const newList = addressList.map(item => {
            if (item._id === id) {
              return { ...item, isDefault: false };
            }
            return item;
          });
          setAddressList(newList);
        }
      })
      .catch(error => {
        console.error('取消默认地址失败:', error);
      });
  };

  // 复制地址信息（不包含前缀文字）
  const copyAddress = (name, phone, address) => {
    const copyText = `${name || '黄文博'}
${phone || '13832023862'}
${address || '河北省保定市莲池区 菜鸟驿站河北科技学院图书馆'}`;
    navigator.clipboard.writeText(copyText)
      .then(() => {
        alert('地址信息已复制到剪贴板');
      })
      .catch(error => {
        console.error('复制失败:', error);
        alert('复制失败，请手动复制');
      });
  };

  // 新增收货地址
  const addNewAddress = () => {
    // 这里可以跳转到新增地址页面
    navigate('/add');
  };

  return (
    <div style={{ background: '#fff', minHeight: '100vh', paddingBottom: '80px' }}>
      {/* 顶部栏 */}
      <div style={{
        position: 'sticky',
        top: 0,
        background: '#fff',
        zIndex: 10,
        padding: '16px 0 8px 0',
        borderBottom: '1px solid #f0f0f0',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
      }}>
        <div style={{ position: 'absolute', left: '16px', top: '50%', transform: 'translateY(-50%)' }}>
          <span onClick={exitManagement} style={{ cursor: 'pointer', fontSize: '18px' }}>←</span>
        </div>
        <div style={{ fontWeight: 'bold', fontSize: '18px', color: '#222' }}>
          收货地址
        </div>
        <div style={{ position: 'absolute', right: '16px', top: '50%', transform: 'translateY(-50%)' }}>
          <span 
            style={{ fontSize: '14px', color: '#ff4d4f', cursor: 'pointer' }}
            onClick={exitManagement}
          >
            退出管理
          </span>
        </div>
      </div>

      {/* 地址列表 */}
      <div style={{ padding: '16px 0 0 0' }}>
        {addressList.map((item, index) => (
          <div
            key={item._id}
            style={{
              background: item.isDefault ? '#f8fffa' : '#fafbfc',
              border: item.isDefault ? '1.5px solid #19c2a6' : 'none',
              borderRadius: 12,
              margin: '0 16px 16px 16px',
              padding: '16px',
              boxShadow: item.isDefault ? '0 0 0 2px #e6f7f1' : 'none',
              position: 'relative',
              minHeight: 80
            }}
          >
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: 6, justifyContent: 'space-between' }}>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <span style={{ fontWeight: 'bold', fontSize: 15, color: '#222', marginRight: 8 }}>{item.name || '黄文博'}</span>
                <span style={{ color: '#666', fontSize: 15 }}>{item.phone || '13832023862'}</span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <input
                  type="radio"
                  checked={item.isDefault}
                  onChange={() => {
                    if (item.isDefault) {
                      cancelDefault(item._id);
                    } else {
                      setDefault(item._id);
                    }
                  }}
                  style={{ marginRight: 4 }}
                />
                <span style={{ color: '#666', fontSize: 14 }}>默认</span>
              </div>
            </div>
            <div style={{ color: '#444', fontSize: 14, marginBottom: 0, position: 'relative' }}>
              {item.address || '河北省保定市莲池区 菜鸟驿站河北科技学院图书馆'}
              {item.isDefault && (
                <span style={{
                  background: '#ff4d4f',
                  color: '#fff',
                  fontSize: 13,
                  borderRadius: 16,
                  padding: '2px 12px',
                  marginTop: 8,
                  display: 'inline-block',
                  fontWeight: 'bold'
                }}>默认</span>
              )}
            </div>
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 8 }}>
              {item.isDefault ? (
                <button style={{ marginRight: 8, color: '#666' }} onClick={() => cancelDefault(item._id)}>取消默认</button>
              ) : (
                <button style={{ marginRight: 8, color: '#666' }} onClick={() => setDefault(item._id)}>设为默认</button>
              )}
              <button style={{ marginRight: 8, color: '#666' }} onClick={() => openDeleteModal(item._id)}>删除</button>
              <button style={{ color: '#666' }} onClick={() => copyAddress(item.name, item.phone, item.address)}>复制</button>
            </div>
          </div>
        ))}
      </div>

      {/* 新增收货地址按钮 */}
      <div style={{
        position: 'fixed',
        left: 0,
        right: 0,
        bottom: 0,
        background: 'transparent',
        zIndex: 100,
        padding: '0 0 24px 0',
        display: 'flex',
        justifyContent: 'center'
      }}>
        <button
          style={{
            width: '92%',
            height: 44,
            background: '#ff4d4f',
            color: '#fff',
            border: 'none',
            borderRadius: 24,
            fontSize: 16,
            fontWeight: 'bold',
            letterSpacing: 2,
            marginTop: 8,
            boxShadow: '0 2px 8px rgba(255,77,79,0.08)',
            cursor: 'pointer'
          }}
          onClick={addNewAddress}
        >
          新增收货地址
        </button>
      </div>

      {/* 删除确认模态框 */}
      {showModal && (
        <div style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          background: 'rgba(0, 0, 0, 0.5)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          zIndex: 200
        }}>
          <div style={{
            background: '#fff',
            borderRadius: 12,
            width: '80%',
            maxWidth: 400,
            padding: 20,
            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)'
          }}>
            <div style={{ fontSize: 18, fontWeight: 'bold', marginBottom: 16, textAlign: 'center' }}>
              确认删除
            </div>
            <div style={{ fontSize: 14, color: '#666', marginBottom: 24, textAlign: 'center' }}>
              确定要删除这个地址吗？删除后将无法恢复。
            </div>
            <div style={{ display: 'flex', justifyContent: 'center', gap: 16 }}>
              <button
                style={{
                  padding: '8px 24px',
                  background: '#f5f5f5',
                  color: '#333',
                  border: 'none',
                  borderRadius: 8,
                  fontSize: 16,
                  cursor: 'pointer'
                }}
                onClick={closeModal}
              >
                取消
              </button>
              <button
                style={{
                  padding: '8px 24px',
                  background: '#ff4d4f',
                  color: '#fff',
                  border: 'none',
                  borderRadius: 8,
                  fontSize: 16,
                  cursor: 'pointer'
                }}
                onClick={confirmDelete}
              >
                确认
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default AddressManagement;